package com.fengye.demo.event.listener;

import com.fengye.demo.event.WfStartEvent;
import com.fengye.demo.service.ICustomerService;
import com.fengye.demo.service.WorkflowService;
import com.fengye.demo.vo.WorkflowVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Optional;

/**
 * @author fengyexjtu@126.com
 * @since 2022-10-05
 */
@Service
@Slf4j
public class WfEventListener {
    
    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private ICustomerService customerService;
    
    @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK, value = WfStartEvent.class)
    public void wfStartEventHandler(WfStartEvent wfStartEvent){
        log.info("WfEventListener.AFTER_ROLLBACK start");
        log.info("WfEventListener.AFTER_ROLLBACK start ===> {}", wfStartEvent);

        WorkflowVO workflowVO = wfStartEvent.getWorkflowVO();
        workflowVO.setReason("发生了异常,将要回滚日志");
        if(isEvent()){
            log.info("回滚日志");
            workflowService.cancel(workflowVO);
            Optional.ofNullable(workflowVO.getWfLogId()).ifPresent(it -> {
                workflowService.rollback(it);
            });
        }
        log.info("WfEventListener.AFTER_ROLLBACK end");
    }


    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, value = WfStartEvent.class)
    public void wfStartEventCommitHandler(WfStartEvent wfStartEvent){
        log.info("WfEventListener.AFTER_COMMIT start");
        WorkflowVO workflowVO = wfStartEvent.getWorkflowVO();
        log.info("WfEventListener.AFTER_COMMIT start ===> {}", workflowVO);
        int id = customerService.save();
        workflowVO.setWfLogId(String.valueOf(id));
        log.info("WfEventListener.AFTER_COMMIT end");
    }
    
    private boolean isEvent() {
        return true;
    }
}
